﻿using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;

namespace MyAuthCore.Api
{
    public class WebSocketManager
    {
        private Dictionary<string, WebSocket> dicSocket = new Dictionary<string, WebSocket>();
        public WebSocketManager()
        {
            Task t = new Task(() =>
            {
                while (true)
                {
                    Thread.Sleep(5000);
                    if(dicSocket.Count>=0)
                    {
                        foreach (var temp in dicSocket)
                        {
                            var headbeat = temp.Key + "|" + DateTime.Now.ToString("yyyyMMddHHmmss");
                            var buffer = System.Text.Encoding.Default.GetBytes(headbeat);
                            temp.Value.SendAsync(new ArraySegment<byte>(buffer),  WebSocketMessageType.Text,true, CancellationToken.None);
                        }
                    }
                }
            });
            t.Start();

        }
        /// <summary>
        /// 响应处理
        /// </summary>
        /// <returns></returns>
        public async Task EchoLoop(HttpContext context, WebSocket webSocket)
        {
            dicSocket.Add(context.Session.Id, webSocket);
            var buffer = new byte[1024 * 4];
            WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            while (!result.CloseStatus.HasValue)
            {
                string str = System.Text.Encoding.Default.GetString(buffer).TrimEnd('\0');
                Console.WriteLine("服务器收到消息：" + str);

                result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            }
            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
            dicSocket.Remove(context.Session.Id);
        }

    }
}
